package com.dome.server;

import com.alibaba.fastjson.JSON;
import com.dome.common.exception.DomeException;
import com.dome.common.pojo.PageResponse;
import com.dome.common.pojo.Pagination;
import com.dome.dao.entity.Dept;
import com.dome.dao.entity.DeptExample;
import com.dome.dao.entity.Tickets;
import com.dome.dao.entity.TicketsExample;
import com.dome.dao.mapper.DeptMapper;
import com.dome.dao.mapper.TicketsMapper;
import com.dome.pojo.Dept.DeptReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class DeptServer {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private TicketsMapper ticketsMapper;

    /**
     * 新增部门
     * @param req
     */
    public void addDept(DeptReq req) {

        //参数校验
        paramValidated(req);

        List<Dept> list = queryDeptList(req.getDeptId());
        if (!CollectionUtils.isEmpty(list)){
            log.info("DeptServer.addDept 部门编号重复 request: {}", JSON.toJSONString(req));
            throw new DomeException("部门编号重复");
        }
        Dept dept = new Dept();
        dept.setDeptId(req.getDeptId());
        dept.setDeptName(req.getDeptName());
        deptMapper.insertSelective(dept);

    }

    /**
     * 参数校验
     * @param req
     */
    private void paramValidated(DeptReq req) {
        if (StringUtils.isEmpty(req.getDeptId()) || StringUtils.isEmpty(req.getDeptName())){
            log.info("DeptServer.paramValidated 部门编号或部门名称不能为空 request: {}", JSON.toJSONString(req));
            throw new DomeException("部门编号或部门名称不能为空");
        }
        if (req.getDeptName().length() > 128){
            log.info("DeptServer.paramValidated 部门名称过长 request: {}", JSON.toJSONString(req));
            throw new DomeException("部门名称过长");
        }
        String regex = "^\\d{8}$";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(req.getDeptId());
        if (!matcher.matches()) {
            log.info("DeptServer.paramValidated 部门编号必须位数字、长度为8 request: {}", JSON.toJSONString(req));
            throw new DomeException("部门编号必须位数字、长度为8");
        }
    }

    /**
     * 按部门编号删除
     * @param req
     */
    public void deleteDept(DeptReq req) {
        if (StringUtils.isEmpty(req.getDeptId())){
            log.info("DeptServer.deleteDept 部门编号不能为空 request: {}", JSON.toJSONString(req));
            throw new DomeException("部门编号不能为空");
        }
        //验证是否有已经分配的部门
        TicketsExample ticketsExample = new TicketsExample();
        TicketsExample.Criteria ticketsExampleCriteria = ticketsExample.createCriteria();
        ticketsExampleCriteria.andHandleDeptIdEqualTo(req.getDeptId());
        List<Tickets> ticketsList = ticketsMapper.selectByExample(ticketsExample);
        if (CollectionUtils.isEmpty(ticketsList)){
            log.info("DeptServer.deleteDept 无法删除，该部门已被分派任务 request: {}", JSON.toJSONString(req));
            throw new DomeException("无法删除，该部门已被分派任务");
        }

        DeptExample example = new DeptExample();
        DeptExample.Criteria criteria = example.createCriteria();
        criteria.andDeptIdEqualTo(req.getDeptId());
        deptMapper.deleteByExample(example);
    }


    /**
     * 按部门编号修改部门名称
     * @param req
     */
    public void updateDept(DeptReq req) {
        //参数校验
        paramValidated(req);

        List<Dept> depts = queryDeptList(req.getDeptId());
        if (CollectionUtils.isEmpty(depts)){
            log.info("DeptServer.updateDept 部门编号不存在 request: {}", JSON.toJSONString(req));
            throw new DomeException("部门编号不存在");
        }
        Dept dept = depts.get(0);
        dept.setDeptName(req.getDeptName());
        deptMapper.updateByPrimaryKeySelective(dept);
    }

    public List<Dept> queryDeptList(String deptId){
        DeptExample example = new DeptExample();
        DeptExample.Criteria criteria = example.createCriteria();
        criteria.andDeptIdEqualTo(deptId);
        List<Dept> depts = deptMapper.selectByExample(example);
        return depts;
    }

    /**
     * 分页查询
     * @param req
     */
    public PageResponse<Dept> queryDept(DeptReq req) {

        Pagination<Dept> pagination = new Pagination<>();
        pagination.setPageNo(req.getPageNo());
        pagination.setPageSize(req.getPageSize());
        DeptExample example = new DeptExample();
        DeptExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNoneEmpty(req.getDeptId())){
            criteria.andDeptIdEqualTo(req.getDeptId());
        }
        if (StringUtils.isNoneEmpty(req.getDeptName())){
            criteria.andDeptNameEqualTo(req.getDeptName());
        }
        long count = deptMapper.countByExample(example);
        if (count == 0L){
            return PageResponse.ofPage(pagination);
        }
        RowBounds bounds = new RowBounds(req.getPageNo(), req.getPageSize());
        List<Dept> list = deptMapper.selectByExampleWithRowbounds(example, bounds);
        pagination.setTotalItemCount(count);
        pagination.setTotalPageCount((count + req.getPageNo() - 1) / req.getPageSize());
        pagination.setData(list);
        return PageResponse.ofPage(pagination);
    }
}
